package com.cx.base.day23_Redis.jedis;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * @Author: songyahui
 * @Date: 2020/8/3 20:15
 * @Version 1.0
 */
public class RedisDemo03_RedisTransaction {
    public static void main(String[] args) {
        Jedis jedis = null;
        Transaction multi = null;
        try {
            jedis = new Jedis("127.0.0.1", 6379);
            jedis.select(6);
            System.out.println(jedis.ping());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("hello", "world");
            jsonObject.put("name", "song");
            String result = jsonObject.toJSONString();
//            监听key值
            jedis.watch(result);
//            需要在watch方法执行后再执行multi方法
            multi = jedis.multi();
//            开启事务
            multi.set("user1", result);
            multi.set("user2", result);
//            int i = 1/0; //错误，但是不会影响其它命令，因此事务无原子性，而命令有原子性
            multi.exec();
        } catch (Exception e) {
            multi.discard();
            e.printStackTrace();
        } finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            if (jedis != null) {
                jedis.close();
            }
            if (multi != null) {
                multi.close();
            }
        }
    }
}
